package com.news.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.news.common.*;
import com.news.common.file.FileUtils;
import com.news.entity.SysFile;
import com.news.entity.SysUser;
import com.news.service.SysFileService;
import com.news.service.SysUserService;
import io.swagger.annotations.Api;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 *
 */
@Api(tags = {"用户管理"})
@Controller
@RequestMapping({"/user","/home/user"})
public class UserController {

    private static  final Logger logger= LoggerFactory.getLogger(UserController.class);

    @Value("${com.cgx.security.md5.key}")
    private String md5Key;

    @Autowired
    SysFileService fileService;

    @Autowired
    SysUserService userService;

    @Value("${com.cgx.file.baseFilePath}")
    private String baseFilePath;

    //跳到管理员添加页面
    @RequestMapping("addAdminPage")
    public String addAdminPage(Model model){
        return "admin/add";
    }

    //跳到管理员编辑页面
    @RequestMapping("editAdminPage")
    public String editAdminPage(Model model,HttpSession session){
        SysUser admin = ToolsUtils.getLoginUser(session);
        model.addAttribute("user",admin);
        return "admin/edit";
    }

    //跳到用户添加页面
    @RequestMapping("addPage")
    public String addPage(Model model){
        return "user/add";
    }

    //跳到前台用户详情页面
    @RequestMapping("homeDetail")
    public String addPage(Model model,Long id){
        SysUser user = userService.getById(id);
        model.addAttribute("user",user);
        return "home/user/detail";
    }
    //跳到前台用户详情页面
    @RequestMapping("homeEditPage")
    public String homeEditPage(Model model,Long id){
        SysUser user = userService.getById(id);
        model.addAttribute("user",user);
        return "home/user/edit";
    }

    /**
     * 后台用户登录
     * @param user
     * @param session
     * @param verifyCode
     * @return
     */

//    和后台数据进行交互，看是否
    @RequestMapping("/checkLogin")
    @ResponseBody
    public ResponseBean checkLogin(SysUser user, HttpSession session, @RequestParam String verifyCode) {
        //首先验证验证码是否存在
        String trueVerifyCode = (String) session.getAttribute("verifyCode");
        if (trueVerifyCode == null) {
            return ResultUtil.error(CommonEnum.REFRESH_VERIFYCODE);
        }
        //判断验证码是否输入正确（验证码忽略大小写）
        if (!trueVerifyCode.equalsIgnoreCase(verifyCode)) {
            return ResultUtil.error(CommonEnum.ERROR_VERIFYCODE);
        }
        QueryWrapper queryWrapper=new QueryWrapper();
//        根据code查询其中的字段信息
        queryWrapper.eq("code",user.getCode());
//        将查询出来的信息存放在一起
        List<SysUser> list = userService.list(queryWrapper);
        //判断是否存在当前用户
        if (ToolsUtils.isEmpty(list)) {
            return ResultUtil.error(CommonEnum.NO_USER_EXIST);
        }
        //判断密码是否正确
        if (!MD5Util.md5Verify(user.getPassword(), this.md5Key, list.get(0).getPassword())) {
            return ResultUtil.error( CommonEnum.INVALID_PASSWORD);
        }
        //通过所有验证之后
        //存放用户信息
        session.setAttribute("user", list.get(0));
        //设置登录用户的权限
        session.setAttribute("type", list.get(0).getType());
        return ResultUtil.success( "登录成功！");
    }

    /**
     * 批量导入用户
     * @param file
     * @return
     */
    @RequestMapping("upload")
    @ResponseBody
    public ResponseBean uploadUser(MultipartFile file){
        if(file==null||file.isEmpty()){
            return  ResultUtil.error("请上传文件！");
        }
        String originalFilename = file.getOriginalFilename();
        String extendName = "."+FileUtils.getExtension(file);
//        String extendName = originalFilename.substring(originalFilename.lastIndexOf("."));
        logger.debug("file.getResource:"+file.getResource());
        String saveFileName= UUID.randomUUID().toString().replaceAll("-","")+extendName;
        File saveFile=new File(baseFilePath+File.separator+saveFileName);
        if(!saveFile.getParentFile().exists()){
            saveFile.getParentFile().mkdirs();
        }
        try {
            //保存文件到最终路径
            file.transferTo(saveFile);
            XSSFWorkbook workbook=new XSSFWorkbook(new FileInputStream(saveFile));
            XSSFSheet sheet = workbook.getSheetAt(0);
            int rows = sheet.getPhysicalNumberOfRows();
            if(rows<2){
                return  ResultUtil.error("上传文件为空！");
            }
            for(int i=1;i<rows;i++){
                XSSFRow row = sheet.getRow(i);
                String name = ToolsUtils.getValFromCell(row.getCell(0));//用户名称
                String code = ToolsUtils.getValFromCell(row.getCell(1));//登录账号
                String mobile = ToolsUtils.getValFromCell(row.getCell(2));//手机号
                String password = ToolsUtils.getValFromCell(row.getCell(3));//密码
                String email = ToolsUtils.getValFromCell(row.getCell(4));//邮箱
                String sex = ToolsUtils.getValFromCell(row.getCell(5)).equals("男")?"0":"1";//性别
                if(!RegexUtil.checkEmail(email)||!RegexUtil.checkMobile(mobile)){
                    logger.debug("邮箱{}或手机号{}不合法，本条不插入",email,mobile);
                    continue;
                }
                String type = ToolsUtils.getValFromCell(row.getCell(6));//0 管理员 ；1 学生 ； 2 教师；3 官微如共青团账号
                switch (type){
                    case "学生":type="1";break;
                    case "教师":type="2";break;
                    case "官微":type="3";break;
                    default:type="1";break;
                }
                QueryWrapper<SysUser> queryWrapper=new QueryWrapper();
                queryWrapper.eq("code",code).or().eq("mobile",mobile);
                List<SysUser> list = userService.list(queryWrapper);
                if(!ToolsUtils.isEmpty(list)){
                    logger.debug("当前账号或密码已经存在，即将跳过！");
                    continue;
                }
                SysUser user=new SysUser();
                user.setCode(code);
                user.setName(name);
                user.setMobile(mobile);
                user.setEmail(email);
                user.setPassword(MD5Util.md5(password,md5Key));
                user.setSex(sex);
                user.setType(Integer.parseInt(type));
                userService.save(user);
            }
            return ResultUtil.success("导入成功！");

        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        }
        return ResultUtil.error();
    }


    //用户添加
    @RequestMapping("add")
    @ResponseBody
    public ResponseBean addUser(SysUser user, MultipartFile file,Model model){
        logger.debug("addSysUser:"+user);
        if(user==null){
            return  ResultUtil.error(CommonEnum.BAD_PARAM);
        }
        String mobile = user.getMobile();
        if(StringUtils.isEmpty(mobile)||!RegexUtil.checkMobile(mobile)){
            logger.error("手机号为空！");
            return  ResultUtil.error("手机号不合法！");
        }
        if(StringUtils.isEmpty(user.getCode())){
            return ResultUtil.error("登录账号为空！");
        }
        QueryWrapper<SysUser> queryWrapper=new QueryWrapper();
        queryWrapper.eq("code",user.getCode()).or().eq("mobile",mobile);
        List<SysUser> pageUserList = userService.list(queryWrapper);
        if(ToolsUtils.isNotEmpty(pageUserList)){
            return ResultUtil.error("手机号或账号已存在！");
        }
        String password=StringUtils.isEmpty(user.getPassword())?"123456":user.getPassword();
        //对密码进行MD5盐值加密，数据库保存密码的密文
        //MD5Util.md5(password,md5Key  md5key就是盐值
        user.setPassword(MD5Util.md5(password,md5Key));
        boolean add = userService.save(user);
        logger.debug("用户添加结果："+user);
        //保存文件并更新saveName到user.field1
        if (file!=null&&!file.isEmpty()) {
            SysFile sysFile=new SysFile();
            sysFile.setObjectId(user.getId());
            sysFile.setField5((userService.getById(sysFile.getObjectId())).getName());
            sysFile.setCategoryCode(ComCodeEnum.category_code_user);
            SysFile saveFile=fileService.saveOrUpdateFile(sysFile,file);
            if(saveFile!=null&&!StringUtils.isEmpty(saveFile.getSaveName())){
                user.setField1(saveFile.getSaveName());
            }
            userService.updateById(user);
        }
        return ResultUtil.successData(user);
    }
    /*用户注册*/
    @RequestMapping("/register")
    @ResponseBody
    public ResponseBean registerUser(SysUser user, MultipartFile file, @RequestParam String verifyCode,HttpSession session){

        String trueVerifyCode = (String)session.getAttribute("verifycode");

        if (trueVerifyCode == null) {
            return ResultUtil.error(CommonEnum.REFRESH_VERIFYCODE);
        }
        //判断验证码是否输入正确（验证码忽略大小写）
        if (!trueVerifyCode.equalsIgnoreCase(verifyCode)) {
            return ResultUtil.error(CommonEnum.ERROR_VERIFYCODE);
        }

        if(user == null){
            return ResultUtil.error(CommonEnum.BAD_PARAM);
        }
        String name = user.getName();
        if (StringUtils.isEmpty(name)){
            return ResultUtil.error("姓名为空");
        }
        if (StringUtils.isEmpty(user.getCode())){
            return ResultUtil.error("账号为空");
        }
        /*查询是否存在*/
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code",user.getCode());
        List<SysUser> lists = userService.list(queryWrapper);
        if (ToolsUtils.isNotEmpty(lists)){
            return ResultUtil.error("账号已经存在");
        }
        /*密码为空默认是123456*/
        String password = StringUtils.isEmpty(user.getPassword())?"123456":user.getPassword();
        //对密码进行MD5盐值加密，数据库保存密码的密文
        //MD5Util.md5(password,md5Key  md5key就是盐值
        user.setPassword(MD5Util.md5(password,md5Key));
        boolean add = userService.save(user);
        logger.debug("用户注册"+user);
        return ResultUtil.successData(user);
    }

    /**
     * 跳转到用户修改页面
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/editPage/{id}")
    public String editPage(@PathVariable Long id, Model model) {
        model.addAttribute("user", userService.getById(id));
        return "user/edit";
    }


    @RequestMapping("initPwd")
    @ResponseBody
    public ResponseBean initPwd(Long id){
        if(id==null||id<1){
            return ResultUtil.error(CommonEnum.BAD_REQUEST) ;
        }
        SysUser sysUser = userService.getById(id);
        if(sysUser!=null){
            sysUser.setPassword(MD5Util.md5("123456",md5Key));
            sysUser.setUpdateTime(LocalDateTime.now());
            userService.updateById(sysUser);
            return ResultUtil.success() ;
        }
        return ResultUtil.error(CommonEnum.NO_USER_EXIST);
    }

    /**
     * 用户修改
     * @param user
     * @return
     */
    @RequestMapping("/edit")
    @ResponseBody
    public ResponseBean updateById(MultipartFile file, SysUser user) {
        if (user == null) {
            return ResultUtil.error(CommonEnum.BAD_PARAM);
        }
        String mobile = user.getMobile();
        if(StringUtils.isEmpty(mobile)||!RegexUtil.checkMobile(mobile)){
            return ResultUtil.error("手机号不合法！");
        }
        QueryWrapper<SysUser> queryWrapper=new QueryWrapper();
        queryWrapper.ne("id",user.getId())
                .and(e->e.eq("code",user.getCode()).or().eq("mobile",user.getMobile()));
        List<SysUser> sysUsers = userService.list(queryWrapper);
        if(ToolsUtils.isNotEmpty(sysUsers)){
            return ResultUtil.error("手机号或登录账号已经被占用！");
        }
        String password = user.getPassword();
        if(!StringUtils.isEmpty(password)){
            user.setPassword(MD5Util.md5(password,md5Key));
        }else{
            user.setPassword(null);
        }
        if (file!=null&&!file.isEmpty()) {
            SysFile sysFile=new SysFile();
            sysFile.setObjectId(user.getId());
            sysFile.setCategoryCode(ComCodeEnum.category_code_user);
            SysFile saveFile=fileService.saveOrUpdateFile(sysFile,file);
            if(saveFile!=null&&!StringUtils.isEmpty(saveFile.getSaveName())){
                user.setField1(saveFile.getSaveName());
            }
        }
        user.setUpdateTime(LocalDateTime.now());
        boolean update = userService.updateById(user);
        return ResultUtil.success() ;
    }

    /**
     * 跳转用户列表页面
     * @return
     */
    @RequestMapping("/listPage")
    public String userListPage(Model model) {
        return "user/list";

    }

    /**
     * 分页列表查询
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param queryParam 查询参数
     * @param vagueParam 模糊参数
     * @return
     */
    @RequestMapping("/list/{pageNum}/{pageSize}")
    @ResponseBody
    public ResponseBean getList(@PathVariable Integer pageNum, @PathVariable Integer pageSize,
                                SysUser queryParam, String vagueParam, HttpSession session) {
        SysUser loginUser = ToolsUtils.getLoginUser(session);
        QueryWrapper<SysUser> queryWrapper=new QueryWrapper<>();
        if(loginUser.getType()!=0){
            //非管理员则只查看自己的用户信息
            queryWrapper.eq("type",loginUser.getType());
        }

        logger.debug("查询用户列表参数："+queryParam+",pageNum:"+pageNum+",pageSize:"+pageSize);
        queryWrapper.eq(!StringUtils.isEmpty(queryParam.getCode()),"code",queryParam.getCode());
        queryWrapper.and(e->e.like("name",vagueParam).or().like("mobile",vagueParam));
        IPage<SysUser> indexPage = new Page<>(pageNum, pageSize);
        IPage<SysUser> page = userService.page(indexPage, queryWrapper);
        logger.debug("获取的用户列表："+page);
        //获取分页信息
        Map<String, Object> pageInfo = new HashMap<String, Object>();
        pageInfo.put("pageSize", page.getSize());
        pageInfo.put("pageNum", page.getCurrent());
        pageInfo.put("pages", page.getPages());
        pageInfo.put("total", page.getTotal());
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("userList", page.getRecords());
        resultMap.put("pageInfo", pageInfo);
        return new ResponseBean<Map<String, Object>>(true, resultMap, CommonEnum.SUCCESS_REQUEST);
    }

    //修改用户状态
    @RequestMapping("updateState")
    @ResponseBody
    public ResponseBean updateState(Long id,Integer state){
        SysUser user = userService.getById(id);
        user.setState(state);
        userService.updateById(user);
        return ResultUtil.successData(user);
    }


    //批量删除用户
    @RequestMapping("deleteBatchByIds")
    @ResponseBody
    public ResponseBean deleteBatchByIds(@RequestParam List<Integer> idList){
        logger.debug("deleteBatchByIds:"+idList);
        if(idList==null||idList.isEmpty()){
            return  new ResponseBean(false,CommonEnum.BAD_REQUEST);
        }
        boolean delete = userService.removeByIds(idList);
        logger.debug("批量删除结果："+delete);
        return new ResponseBean<Map<String, Object>>(true, null, CommonEnum.SUCCESS_REQUEST);
    }
    //删除单个用户
    @RequestMapping("deleteById")
    @ResponseBody
    public ResponseBean deleteById(@RequestParam Long id){
        logger.debug("deleteById:"+id);
        if(id==null||id<0){
            return  new ResponseBean(false,CommonEnum.BAD_REQUEST);
        }
        boolean delete = userService.removeById(id);
        logger.debug("删除结果："+delete);
        return new ResponseBean<Map<String, Object>>(true, null, CommonEnum.SUCCESS_REQUEST);
    }
}
